package com.ztn.sdk.iot.api.util;

import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class HttpTool {

    private final static Logger log = LoggerFactory.getLogger(HttpTool.class);

    public final static String BASE_URL = "https://core.ztn-tech.com/";

    public static String DEFAULT_CHARSET = "UTF-8";

    public static String token;

    public static String setToken(String t) {
        return token = t;
    }

    public static <T> T doPost(String path, String json, TypeReference<T> typeReference) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(BASE_URL + path);
        httpPost.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());
        httpPost.addHeader("access-token",token);

        StringEntity postEntity = new StringEntity(json, DEFAULT_CHARSET);
        httpPost.setEntity(postEntity);
        try {
            CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpPost);
            if (closeableHttpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                log.error("{} {}", path, closeableHttpResponse.getStatusLine().getStatusCode());
                return null;
            }
            String s = EntityUtils.toString(closeableHttpResponse.getEntity(), DEFAULT_CHARSET);
            return JsonTool.fromJson(s, typeReference);
        } catch (Exception e) {
            log.error("{} {}", path, e.getMessage());
            return null;
        }
    }
}
